<?php
/**
 * Created by PhpStrom
 * User: 郭碧云
 * Date: 2021/7/12 16:26
 * Desc:
 */

namespace App\Service;


use App\Lib\FormulaInterpreter\Compiler;

class QuestionService extends BaseService
{
    protected $modelName = "question";

    /**
     * 生成where
     * @parma $params 接收的搜索数组
     */
    public function getWhere($params){
        unset($params['category']);
        unset($params['group_id']);
        $where=[];
        if (array_key_exists("question", $params) && !empty($params["question"]) && "" != $params["question"] && null != $params["question"]) {
            $where[] =["question","like","%" . $params["question"] . "%"];
        }
        if(array_key_exists("type_id", $params) && !empty($params["type_id"]) && "" != $params["type_id"] && null != $params["type_id"]){
            $where["type_id"] = $params["type_id"];
        }
        if(array_key_exists("creator", $params) && !empty($params["creator"]) && "" != $params["creator"] && null != $params["creator"]){
            $where["creator"] = $params["creator"];
        }
        if(array_key_exists("version_id", $params) && !empty($params["version_id"]) && "" != $params["version_id"] && null != $params["version_id"]){
            $where["version_id"] = $params["version_id"];
        }
        if(array_key_exists("tag_id", $params) && !empty($params["tag_id"]) && "" != $params["tag_id"] && null != $params["tag_id"]){
            $where["tag_id"] = $params["tag_id"];
        }
        if(array_key_exists("level", $params) && !empty($params["level"]) && "" != $params["level"] && null != $params["level"]){
            $where["level"] = $params["level"];
        }
        if(array_key_exists("org_id", $params) && !empty($params["org_id"]) && "" != $params["org_id"] && null != $params["org_id"]){
            $org = (new OrgService())->first(["id"=>$params["org_id"]]);
            $where[] = ['org_code', 'like', $org["code"] . "%"];
        }
        return $where;
    }

    /**获取添加人信息*/
    public function getUser(){
        $data = (new AdminUserService())->getAll(["id", "name","real_name"], ["site_id" => getCurrentSiteId()]);
        foreach ($data as $k=>$v){
            $data[$k]["rname"]=$v["name"]."(".$v["real_name"].")";
        }
        return $data;
    }

    /**
     * 获取数据
     * @param $data 接收的添加数据
     */
    public function getData($data) {
        $data["site_id"] = getCurrentSiteId();
        $data["creator"] = getCurrentUser()["id"];
        //组织机构
        $org = (new OrgService())->first(["id" => $data["org_id"]]);
        $data["org_code"] = $org["code"];
        //科目
        $category=(new CategoryService())->first(["id" => $data["category_id"]]);
        $data["category_path"] = $category["path"];
        //标签
        $data["tag_id"]=empty($data["tag_id"])||null==$data["tag_id"]?0:$data["tag_id"];
        return $this->contentAndAnswer($data);
    }

    /**
     * 计算题处理结果
     * @param $answer 计算题的变量组及结果组数组，格式["x"=>[[1,2,3],[4,5,6],...],"y"=>[["key"=>"Y1","y"=>"公式"],["key"=>"Y2","y"=>"公式"],...],"d"=>["1","2",...]]
     */
    public function getResult($answer){
        foreach ($answer["x"] as $k=>$v){
            $x=[];
            for($i=0;$i<count($v);$i++){
                $x[]="X".($i+1);
            }
            //计算结果
            $formula = str_replace($x,$v,$answer["y"][$k]["y"]);
            if($answer["d"][$k]>0){
                $formula = "number_format(".$formula.", ".$answer["d"][$k].")";
            }
            if($answer["d"][$k]==0){
                $formula = "round(".$formula.")";
            }

            $executable = (new Compiler())->compile($formula);
            $answer["y"][$k]["result"] = $executable->run();
            $answer["y"][$k]["formula"] = $formula;
        }
        return $answer;
    }


    /**
     * 内容及答案
     * @param $data 接收的添加数据
     */
    private function contentAndAnswer($data) {
        //提取答案
        $data["answer"] = [];
        //题型类别
        $type = (new QuestionTypeService())->first(["id" => $data["type_id"]]);
        if ($type["choice_type"] > 0) {
            if($type["choice_type"] == 4){
                $data["answer"]=["objective"=>$data["objective"]];
            }
            //定值
            else if ($type["choice_type"] == 5) {
                $data["answer"] = [$data["directionalAnswer"]];
            }else if($type["choice_type"] == 6){
                //计算
                $data["answer"]=$this->params($data);
            }else{
                //选择
                $data["answer"]=$this->answer($type["choice_type"],$data);
            }
        } else {
            $data["answer"] = [$data["askAnswer"]];
        }
        $data["answer"]=$data["answer"];
        return $data;
    }

    /**
     * 变量处理
     */
    private function params($data){
        $params=[];
        //提取变量
        foreach ($data["X"] as $k=>$v){
            $params["x"][$k]=explode(",",$v);
        }
        //提取结果
        foreach ($data["result"]["name"] as $k=>$v){
            $params["y"][$k]["key"]=$v;
            $params["y"][$k]["y"]=$data["result"]["formula"][$k];
        }
        $params["d"]=$data["result"]["decimals"];
        return $params;
    }
    /**
     * 客观题答案
     */
    private function answer($type,$data){
        $answer=[];$i=0;
        $ansItem = $type==1||$type==4?[$data["oneAnswer"]]:$data["moreAnswer"];
        foreach ($data["content"] as $k => $v) {
            $answer[$i]["option"]=$v;
            foreach ($ansItem as $item) {
                $item==$k?$answer[$i]["flag"]=1:"";
            }
            $i++;
        }
        return $answer;
    }
}
